<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车间任务卡编号" prop="sn" label-width="55">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入车间任务卡编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['mes:card:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['mes:card:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['mes:card:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:card:export']"
        >导出</el-button>
      </el-col>
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="cardList" border style="width: 100%" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="序号" align="center" prop="number" width="80"/>
      <el-table-column label="任务卡状态" align="center" prop="taskState"width="90" >
        <template v-slot = "scope">
          <dict-tag :options="dict.type.card_status" :value="scope.row.taskState"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="车间任务卡id" align="center" prop="id" />-->
      <el-table-column label="生产进度" align="center" width="140">
        <template v-slot="{ row }">
          <div class="demo-progress">
            <el-progress :text-inside="true" :stroke-width="15" :percentage="calculateProgressPercentage(row.planNum, row.proNum)" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="车间任务编号" align="center" prop="sptkSn" width="150"/>
      <el-table-column label="任务卡编号" align="center" prop="sn" width="180"/>
<!--      <el-table-column label="车间任务id" align="center" prop="sptkId" />-->
      <el-table-column label="产品名称" align="center" prop="proName" width="120"/>
      <el-table-column label="产品编码" align="center" prop="proSn" width="150"/>
      <el-table-column label="生产批号" align="center" prop="proLotNumber" width="150" />
      <el-table-column label="计划生产数量" align="center" prop="planNum" width="120"/>
      <el-table-column label="已生产数量" align="center" prop="proNum" width="120"/>
      <el-table-column label="计划开始日期" align="center" prop="planStartDate" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planStartDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划完成时间" align="center" prop="planEndDate" width="130">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planEndDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createdBy" />
      <el-table-column label="创建时间" align="center" prop="createdTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" fixed="right" width="130">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['mes:card:edit']"-->
<!--          >修改</el-button>-->
          <el-button
            size="20"
            type="text"
            icon="el-icon-check"
            @click="handleSigning(scope.row,scope.$index)"
          >执行工序</el-button>
          <el-dropdown>
              <span class="el-dropdown-link">
                <el-icon class="el-icon-more">
                  </el-icon>
                  更多
                </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-check"
                    @click="handleSetQuality(scope.$index)"
                  >质检&报工</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                  >撤销任务卡</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车间任务卡对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车间任务卡编号" prop="sn" >
          <el-input v-model="form.sn" placeholder="请输入车间任务卡编号"/>
        </el-form-item>
        <el-form-item label="生产批号" prop="proLotNumber">
          <el-input v-model="form.proLotNumber" placeholder="请输入生产批号" />
        </el-form-item>
        <el-form-item label="任务卡状态" prop="taskState">
          <el-input v-model="form.taskState" placeholder="请输入任务卡状态" />
        </el-form-item>
        <el-form-item label="计划生产数量" prop="planNum">
          <el-input v-model="form.planNum" placeholder="请输入计划生产数量" />
        </el-form-item>
        <el-form-item label="已生产数量" prop="proNum">
          <el-input v-model="form.proNum" placeholder="请输入已生产数量" />
        </el-form-item>
        <el-form-item label="计划开始日期" prop="planStartDate">
          <el-date-picker clearable
            v-model="form.planStartDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择计划开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划完成时间" prop="planEndDate">
          <el-date-picker clearable
            v-model="form.planEndDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择计划完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 报工对话框 -->
    <el-dialog :title="titleSigning" :visible.sync="openSigning" width="1010px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-divider>工序列表</el-divider><!--分割线-->
        <el-card shadow="always" style="border-radius: 15px;">
          <el-table border style="width: 100%" v-loading="loading" :data="formSigningList">
            <el-table-column label="产品编码" align="center" width="240">
              <template slot-scope="scope" >
                <span>{{scope.row.proName+"/"+scope.row.proSn}}</span>
              </template>
            </el-table-column>
            <el-table-column label="任务卡编号" prop="sn" align="center" width="100">
              <template slot-scope="scope" >
                <span>{{scope.row.sn}}</span>
              </template>
            </el-table-column>
            <el-table-column label="工序" prop="pcsName" align="center" width="140">
              <template slot-scope="scope">
                <el-button type="text" style="color: red;" @click="handlePcsName(scope.row.pcsName)">{{ scope.row.pcsName }}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="绑定设备" prop="eptName" align="center" width="120">
              <template slot-scope="scope" >
                <span>{{scope.row.eptName}}</span>
              </template>
            </el-table-column>
            <el-table-column label="计划生产数量" prop="planNum" align="center" width="110">
              <template slot-scope="scope" >
                <span>{{scope.row.planNum}}</span>
              </template>
            </el-table-column>
            <el-table-column label="生产报工数量" prop="sigNum" align="center" width="210">
              <template slot-scope="scope" >
                <el-input-number v-model="scope.row.sigNum" placeholder="请输入生产报工数量" :min="0" :max="scope.row.planNum" controls :step="1" />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormSigning">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 质检对话框 -->
    <el-dialog :title="titleQuality" :visible.sync="openQuality" width="500px" append-to-body>
      <el-form ref="form" :model="formQuality" :rules="rules" label-width="120px">
        <el-form-item label="已生产报工数量"  >
          {{formQuality.productionNum}}
        </el-form-item>
        <el-form-item label="质检数量" >
          <el-input-number v-model="formQuality.qualityNum" placeholder="请输入质检数量" :min="0" :max="formQuality.productionNum" controls :step="1" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlePcsName('质检')">质检</el-button>
        <el-button type="primary" @click="submitFormQuality">报 工</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listCard, getCard, delCard, addCard, updateCard, getCardProcess} from "@/api/mes/card";
import Vue from "vue";
import {AgvCarService, FourRobotArm, GantryService, MarkingMachine, SixRobotArm} from "@/api/equipmentAPI/equipmentAPI";

export default {
  name: "Card",
  dicts:["card_status"],
  data() {
    return {
      //报工和质检行数
      Index:0,
      //存放已报工数量和质检通过数量
      QualityNumList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车间任务卡表格数据
      cardList: [],
      // 弹出层标题
      title: "",
      titleQuality:"",
      titleSigning:"",
      // 是否显示弹出层
      open: false,
      openQuality:false,
      openSigning:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
      },
      // 表单参数
      form: {},
      formQuality: {
        qualityNum:0,
      },
      formSigningList:[
      ],
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //报工
    handleSigning(row,index){
      this.Index=index;
      const proId = row.proId;
      getCardProcess(proId).then(response=>{
        this.formSigningList = response.rows
        this.formSigningList.forEach((item,index)=>{
         item.planNum=row.planNum-row.proNum;
         item.sn = row.sn;
         item.proName=row.proName;
         item.proSn=row.proSn;
        })
        this.openSigning=true;
        this.titleSigning="报工";
      })
    },
    //质检
    handleSetQuality(index){
      this.formQuality.productionNum=this.QualityNumList[index].sigNum;
      this.Index=index;
      this.openQuality=true;
      this.titleQuality="质检";
    },
    /** 查询车间任务卡列表 */
    getList() {
      this.loading = true;
      listCard(this.queryParams).then(response => {
        this.cardList = response.rows;
        this.cardList.forEach((item, index) => {
          Vue.set(this.QualityNumList, index, {sigNum:0,passQualityNum:0});
        });
        this.total = response.total;
        this.loading = false;
        this.calculateIndex()
      });
    },
    /** 计算列表编号 */
    calculateIndex() {
      this.cardList.forEach((item, index) => {
        this.$set(item, 'number', index + 1);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openQuality=false;
      this.openSigning=false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sn: null,
        sptkId: null,
        proLotNumber: null,
        taskState: null,
        planNum: null,
        proNum: null,
        planStartDate: null,
        planEndDate: null,
        isDeleted: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedDate: null,
        remark: null
      };
      this.resetForm("form");
    },
    //根据计划生产数量和已生产数量计算生产进度的比值
    calculateProgressPercentage(planNum, gbtNum) {
      // 确保计划生产数量和已生产数量都是数字
      if (isNaN(planNum) || isNaN(gbtNum)) {
        return 0;
      }
      if (planNum === 0) {
        // 避免除以零的情况
        return 0;
      }
      // 计算百分比并四舍五入
      return Math.round((gbtNum / planNum) * 100);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    async handlePcsName(pcsName) {
      // 定义一个映射，将pcsName与对应的请求方法关联起来
      const requestMap = {
        '三轴龙门取料': () => GantryService.materialOutbound(),
        'AGV小车移动1': () => AgvCarService.advanceToNextStop(),
        '六轴取料': () => SixRobotArm.fetchFromCar(),
        '打标机打标': () => MarkingMachine.printImage(),
        '六轴放料': () => SixRobotArm.placeToCar(),
        'AGV小车移动2': () => AgvCarService.advanceToNextStop(),
        '质检': () => FourRobotArm.qualityCheck(),
        '三轴龙门放料': () => GantryService.materialInbound(),
        '合格品入库': () => GantryService.qualifiedInbound(),
        '不合格品入库': () => GantryService.nonQualifiedInbound(),
        '返回初始位置': () => AgvCarService.returnToHomeStop(),
        // 添加更多的工序和对应的方法
      };
      // 获取对应的请求方法
      const requestMethod = requestMap[pcsName];
      // 添加日志以确认requestMethod的值
      console.log("pcsName", pcsName);
      console.log("requestMethod", requestMethod);

      if (requestMethod && typeof requestMethod === 'function') {
        try {
          const timeoutPromise = new Promise((_, reject) => {
            setTimeout(() => {
              reject(new Error('请求超时'));
            }, 2000);
          });

          const response = await Promise.race([
            requestMethod(),
            timeoutPromise
          ]);
          if (response.status === 200) {
            this.$modal.msgSuccess("设备调用成功");
          } else {
            this.$modal.msgError("设备调用失败");
          }
        } catch (error) {
          this.$modal.msgWarning("设备未在线");
        }
      } else {
        // 如果requestMethod不存在或不是函数，则提示设备未启用
        this.$modal.msgError("设备未启用");
      }
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车间任务卡";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCard(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改车间任务卡";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.cardList[this.Index].proNum=this.formQuality.qualityNum;
      if( this.cardList[this.Index].proNum< this.cardList[this.Index].planNum)
      {
        this.cardList[this.Index].taskState=0;
      }
      else {
        this.cardList[this.Index].taskState=1;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCard(this.cardList[this.Index]).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCard(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    submitFormSigning(){
      var min = 0;
      this.formSigningList.forEach((item, index) => {
       if(index==0){
          min = item.sigNum;
       }
       else{
         if(min>item.sigNum){
           min = item.sigNum;
         }
       }
      });
      this.QualityNumList[this.Index].sigNum=min;
      this.openSigning=false;
      this.$modal.alertSuccess("工序完成，请质检！")
      console.log("this.signingList[this.qualityIndex]",this.QualityNumList[this.Index])
    },
    submitFormQuality(){
      this.QualityNumList[this.Index].passQualityNum=this.formQuality.qualityNum;
      this.cardList[this.Index].proNum=this.formQuality.qualityNum;
      if( this.cardList[this.Index].proNum< this.cardList[this.Index].planNum)
      {
        this.cardList[this.Index].taskState=0;
      }
      else {
        this.cardList[this.Index].taskState=1;
      }
      console.log("this.cardList[this.Index]",this.cardList[this.Index])
      updateCard(this.cardList[this.Index]).then(response => {
        this.$modal.msgSuccess("报工完成");
        this.openQuality=false;
        this.getList();
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除车间任务卡编号为"' + ids + '"的数据项？').then(function() {
        return delCard(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/card/export', {
        ...this.queryParams
      }, `card_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
